//
//  StatusCache.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/6/14.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit

class StatusCache: NSObject {

    /**
     加载微博数据
     */
    
    class func loadWeiBoStatusData(since_id: Int, max_id: Int, finished: ([[String: AnyObject]]?, error: NSError?)->()){
        
      //1、 从本地数据库取出数据
        loadLocalStatusData(since_id, max_id: max_id) { (dictArr) in
            
            if !dictArr.isEmpty{
                finished(dictArr, error: nil)
                return
            }
        }
        
        //2、从网络请求数据
        let url = "2/statuses/home_timeline.json"
        var params = ["access_token" : UserAccount.getUserAccount()!.access_token!]
        
        // 下拉刷新
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            params["max_id"] = "\(max_id - 1)"
        }
        params["count"] = "10"
        
        NewWorkRequest.shareNewWorkRequest().GET(url, parameters: params, success: { (_, result) in
            
        let dictArr = result!["statuses"] as! [[String: AnyObject]]
            // 缓存数据
            cacheStasusData(dictArr)
            finished(dictArr, error: nil)
        }) { (_, error) in
            finished(nil, error: error)
        }

    }
    
    
    /**
     缓存从网络请求出来的数据
     - parameter stasus:
     */
    class func cacheStasusData(stasus: [[String: AnyObject]]){
        
        let useId =  UserAccount.getUserAccount()!.uid!
        
    let sql = "insert into s_investor(statusId, statusText, userId) values (?, ?, ?);"
        
        FMDBSQLManager.shareSingleManager().dbQueue!.inTransaction { (db, rollback) in
            
            for dict in stasus{
                let statusId = dict["id"]!
                
              // Json->二进制-> 字符串
             let data = try! NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)
             let statusText = String(data: data, encoding: NSUTF8StringEncoding)
                
                do{
                    
                    try db.executeUpdate(sql, statusId, statusText!, useId)
                }
                catch{
                   rollback.memory = true
                }
                
            }
        }
        
    }
    
    
    /**
     从本地数据库加载网络数据
     
     - parameter since_id: <#since_id description#>
     - parameter max_id:   <#max_id description#>
     - parameter finished: <#finished description#>
     */
    class func loadLocalStatusData(since_id: Int, max_id: Int, finished: ([[String: AnyObject]])->()){
        
        // 定义sql语句
        var sql = "SELECT * FROM s_investor "
        if since_id > 0 {
            sql += "WHERE statusId > \(since_id)"
        }
        else if max_id > 0{
            sql += "WHERE statusId < \(max_id)"
        }
          sql += " ORDER BY statusId DESC limit 10;"
        
        // 开启事务
        FMDBSQLManager.shareSingleManager().dbQueue!.inTransaction { (db, rollback) in
            
           let results = db.executeQuery(sql, withArgumentsInArray: nil)
            
            
            var dictArr = [[String: AnyObject]]()
            while results.next(){
                // results.intForColumnIndex(0)
               let str =  results.stringForColumn("statusText")
                // 将json字符串转换为二进制
                let data = str.dataUsingEncoding(NSUTF8StringEncoding)
                
                let dict = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String: AnyObject]
                dictArr.append(dict)
                
            }
             finished(dictArr)
        }
    }
 }
